<template lang="html">
<Card class="user">
  <p slot="title" style="font-size:20px;line-height:32px;height:32px">{{title}}</p>
  <div slot="extra" style="padding-right:32px;">
    <span v-show="type==='base'">
      <Button type="primary" size="small" @click="getStaffs">查询</Button>
      <Button type="primary" size="small" class="ml_5" @click="plus">新建</Button>
      <Button type="primary" size="small" class="ml_5" @click="exportData" :loading="exportLoading">导出</Button>
      <Button size="small" class="ml_5" @click="reset">重置</Button>
    </span>
    <span v-show="['view','plus','edit'].includes(type)">
      <Button type="primary" size="small" @click="save" v-show="type!=='view'" :loading="saveLoading">保存</Button>
      <Button size="small" class="ml_5" @click="type = 'base';getStaffs();">返回</Button>
    </span>
  </div>
  <div v-show="type==='base'">
    <Row class="border-bottom">
      <Form ref="form" :model="form" inline label-position="left">
        <i-col>
          <FormItem label="姓名" prop="name" :label-width="45">
            <div class="position-msg">输入姓名</div>
            <Input v-model="form.name" style="width:180px;"/>
          </FormItem>
          <FormItem label="电话" prop="mobile" :label-width="45">
            <div class="position-msg">输入电话</div>
            <Input v-model="form.mobile" style="width:180px;"/>
          </FormItem>
        </i-col>
        <i-col>
          <FormItem label="城市" prop="province" :label-width="45">
            <div class="position-msg">省</div>
            <Select v-model="address.province" style="width:100px;" @on-change="address.city = '';form.store='';selectChange($event,'region','cityOption')">
              <Option v-for="(v,i) in region" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="city" :label-width="0">
            <div class="position-msg">市</div>
            <Select v-model="address.city" style="width:100px;" @on-change="toSelectShop">
              <Option v-for="(v,i) in cityOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
          <!-- <FormItem prop="district" :label-width="0">
            <div class="position-msg">区</div>
            <Select v-model="address.district" style="width:155px;" @on-change="toSelectShop">
              <Option v-for="(v,i) in distOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem> -->
          <FormItem label="门店" prop="shop" :label-width="45">
            <div class="position-msg">门店</div>
            <Select v-model="form.store" style="width:180px;" clearable @on-clear="clearSelect" :loading="shopLoading"> 
              <Option v-for="(v,i) in shopOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Form>
    </Row>
    <i-table ref="table" :columns="columns" :data="tableData" height="320" :loading="loading"/>
    <div style="text-align: center;margin-top:20px;">
      <Page :total="total" :page-size="pageSize" show-elevator :current.sync="page" @on-change="pageChange"/>
    </div>
  </div>
  <div v-show="['view','plus','edit'].includes(type)">
    <Form class="editForm" ref="userForm" :model="userForm" :rules="userRules" label-position="left" inline>
      <Row>
        <Col>
          <FormItem label="姓名" prop="name" :label-width="50">
            <div class="position-msg">输入姓名</div>
            <Input v-model="userForm.name" style="width:180px;" :readonly="type==='view'"/>
          </FormItem>
        </Col>
        <Col>
          <FormItem label="电话" prop="mobile" :label-width="50" :error="errorMsg">
            <div class="position-msg">输入电话</div>
            <Input v-model="userForm.mobile" style="width:180px;" :readonly="type==='view'"/>
          </FormItem>
        </Col>
        <Col>
          <FormItem label="城市" :label-width="50">
            <div class="position-msg">省</div>
            <Select v-model="address.province" style="width:100px;" @on-change="address.city = '';selectChange($event,'region','cityOption')" :readonly="type==='view'">
              <Option v-for="(v,i) in region" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
          <FormItem :label-width="0">
            <div class="position-msg">市</div>
            <Select v-model="address.city" style="width:100px;" @on-change="toSelectShop" :readonly="type==='view'">
              <Option v-for="(v,i) in cityOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
          <!-- <FormItem :label-width="0">
            <div class="position-msg">区</div>
            <Select v-model="address.district" style="width:155px;" @on-change="toSelectShop" :readonly="type==='view'">
              <Option v-for="(v,i) in distOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem> -->
        </Col>
        <Col>
          <FormItem label="门店" prop="store" :label-width="50">
            <div class="position-msg">门店</div>
            <Select v-model="userForm.store" style="width:180px;" clearable @on-clear="clearSelect" :readonly="type==='view'">
              <Option v-for="(v,i) in shopOption" :key="i" :value="v.id">{{v.name}}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
  <commonModal :visible.sync="visible" @confirm="confirm" @close="visible = false" :loading="modalLoading">
    {{disableMsg}}
  </commonModal>
</Card>
</template>

<script>
import {
  getStaffs,
  getsStaffstTrains,
  createStaffs,
  updateStaffs,
  getStores,
  staffsExport
} from 'api'
import { mapGetters } from 'vuex'
export default {
  name: 'user',
  data() {
    return {
      form: {
        name: '',
        mobile: '',
        store: ''
      },
      columns: [
        {
          title: '姓名',
          key: 'name',
          align: 'center'
        },
        {
          title: '联系电话',
          key: 'mobile',
          align: 'center',
          width: 160
        },
        {
          title: '培训状态',
          key: 'training_status',
          align: 'center',
          width: 100,
          render: (h, params) => (
            <div>
              <span class="green">{params.row.train_count}</span>/
              <span>{params.row.join_count}</span>
            </div>
          )
        },
        {
          title: '考试状态',
          key: 'success_count',
          align: 'center',
          className: 'green'
        },
        {
          title: '门店',
          key: 'shop',
          align: 'center',
          width: 205,
          className: 'shop-cell',
          render: (h, params) => (
            <div>{this.renderStore(params.row.store_detail)}</div>
          )
        },
        {
          title: '操作',
          align: 'center',
          width: 180,
          render: (h, params) => (
            <div>
              <span
                type="text"
                class="span-btn"
                onClick={() => this.tableClick('view', params)}
              >
                查看
              </span>
              |
              <span
                type="text"
                class="span-btn"
                onClick={() => this.tableClick('edit', params)}
              >
                编辑
              </span>
              |
              <span
                type="text"
                class="span-btn dis"
                onClick={() => this.tableClick('disable', params)}
              >
                {params.row.is_enable ? '停用' : '启用'}
              </span>
            </div>
          )
        }
      ],
      tableData: [],
      total: 60,
      type: 'base',
      address: {
        province: '',
        city: ''
      },
      userForm: {
        name: '',
        mobile: '',
        store: '',
        is_enable: true
      },
      userRules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话',
            trigger: 'blur'
          },
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: '请输入有效的电话',
            trigger: ['change', 'blur']
          }
        ],
        store: [
          {
            required: true,
            message: '请输入门店'
          }
        ]
      },
      visible: false,
      disableMsg: '',
      rowParams: {},
      loading: false,
      page: 1,
      pageSize: 20,
      cityOption: [],
      distOption: [],
      shopOption: [],
      saveLoading: false,
      modalLoading: false,
      shopLoading: false,
      errorMsg: '',
      exportLoading: false
    }
  },
  computed: {
    title() {
      switch (this.type) {
        case 'base':
          return '员工管理'
          break
        case 'plus':
          return '新建'
          break
        case 'edit':
          return '编辑'
          break
        default:
          break
      }
    },
    ...mapGetters(['stores', 'region'])
  },
  created() {
    this.getStaffs()
  },
  methods: {
    reset() {
      this.$refs.form.resetFields()
      this.clearSelect()
      this.getStaffs()
    },
    plus() {
      this.$refs.userForm.resetFields()
      this.clearSelect()
      this.type = 'plus'
    },
    save() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          this.errorMsg = ''
          this.saveLoading = true
          let res
          switch (this.type) {
            case 'plus':
              res = await createStaffs(this.userForm).catch(e => {
                if (e['mobile']) {
                  this.errorMsg = '此号码已占用'
                  this.saveLoading = false
                }
              })
              break
            case 'edit':
              res = await updateStaffs({
                ...this.userForm,
                id: this.rowParams.id
              })
              break
            default:
              break
          }
          if (res) {
            this.$Message.success(
              this.type === 'edit' ? '修改成功！' : '创建成功！'
            )
            this.$refs.userForm.resetFields()
            this.clearSelect()
            this.type = 'base'
            this.getStaffs()
          }
          this.saveLoading = false
        }
      })
    },
    async tableClick(type, params) {
      this.rowParams = params.row
      this.clearSelect()
      switch (type) {
        case 'edit':
        case 'view':
          const storeDetail = params.row.store_detail
          this.address.province = this.region.find(
            v => v.name === storeDetail.province
          ).id
          this.selectChange(this.address.province, 'region', 'cityOption')
          this.address.city = this.cityOption.find(
            v => v.name === storeDetail.city
          ).id
          await this.toSelectShop(this.address.city)
          Object.keys(this.userForm).forEach(
            key => (this.userForm[key] = params.row[key])
          )
          this.type = type
          break
        case 'disable':
          this.disableMsg = params.row.is_enable
            ? '确定停用此员工？'
            : '确定启用此员工？'
          this.visible = true
          break
        default:
          break
      }
    },
    async confirm() {
      this.modalLoading = true

      let res = await updateStaffs({
        is_enable: !this.rowParams.is_enable,
        id: this.rowParams.id
      })
      if (res) {
        this.getStaffs()
      }
      this.modalLoading = false
      this.visible = false
    },
    async getStaffs() {
      this.loading = true
      let res = await getStaffs({
        ...this.form,
        store__region__parent: this.address.province,
        store__region: this.address.city,
        is_enable: true,
        page: this.page,
        page_size: this.pageSize
      })
      if (res) {
        let data = []
        res.results.forEach(async v => {
          let obj = await getsStaffstTrains({ id: v.id })
          let back = {
            ...v,
            pass: obj.pass_count,
            train_count: obj.train_count,
            total: obj.total,
            exam_status: obj.results
          }
          data.push(back)
        })
        this.total = res.count
        this.pageSize = res.page_size
        this.page = res.page
        this.tableData = data
      }
      this.loading = false
    },
    pageChange(val) {
      this.page = val
      this.getStaffs()
    },
    renderStore(store) {
      return `${store.province} ${store.city} \r\n ${store.name}`
    },
    selectChange(val, key, opt) {
      if (!val) {
        return
      }
      this[opt] = this[key].find(v => v.id === val).child
    },
    clearSelect() {
      Object.keys(this.address).forEach(key => (this.address[key] = ''))
      this.form.store = ''
      this.userForm.store = ''
      this.cityOption = []
      this.distOption = []
      this.shopOption = []
    },
    async toSelectShop(region) {
      this.form.store = ''
      if (!region) {
        return
      }
      this.shopLoading = true
      let res = await getStores({ region })
      if (res) {
        this.shopOption = res.results.filter(v => v.is_enable)
      }
      this.shopLoading = false
    },
    async exportData() {
      this.exportLoading = true
      let res = await staffsExport({
        ...this.form,
        store__region__parent: this.address.province,
        store__region: this.address.city,
        is_enable: true,
        page: this.page,
        page_size: this.pageSize
      })
      if (res) {
        const eleLink = document.createElement('a')
        eleLink.download = '员工管理.csv'
        eleLink.style.display = 'none'
        const blob = new Blob(['\ufeff' + res], { type: 'text/csv' }) //解决大文件下载失败
        eleLink.setAttribute('href', URL.createObjectURL(blob))
        eleLink.click()
      }
      this.exportLoading = false
    }
  }
}
</script>

<style lang="stylus">
.user {
  height: 600px;

  td.shop-cell {
    .ivu-table-cell {
      div {
        padding: 0 20px;
        // text-align: left;
        word-break: keep-all;
      }
    }
  }
}
</style>
